package cn.fate.core.system;

import cn.fate.core.common.*;
import cn.fate.core.dao.basic.entity.Staff;
import cn.fate.core.dto.StaffDto;
import cn.fate.core.service.basic.StaffService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

/**
 * @program: FtCore
 * @description: 登录
 * @author: xubo
 * @create: 2021-09-13 17:26
 **/
public class LoginController {

    @Autowired
    private StaffService staffService;

    @Autowired
    private RedisUtil redisUtil;

    @PostMapping(value = "/checkLogin", produces = "application/json;charset=UTF-8")
    public ResponseBean checkLogin(HttpServletRequest request, @RequestBody Staff staff) throws Exception {

        String staffNo = staff.getStaffNo();
        String password =  staff.getStaffPwd();
        password= DescUtil.decrypt(password, DescUtil.upKey);
        QueryWrapper<Staff> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("staff_no",staffNo);
        Staff realStaff = staffService.getOne(queryWrapper);
        password = Md5Util.getMD5String(realStaff.getStaffNo()+password);
        if (realStaff!=null&&staff.getStaffPwd().equals(password)){
            String accessToken = UUID.randomUUID().toString();
            redisUtil.set(RedisKey.ACCESS_TOKEN + accessToken, realStaff, 24 * 3600);
            StaffDto staffDto = new StaffDto();
            staffDto.setToken(accessToken);
            staffDto.setStaffId(staff.getStaffId());
            staffDto.setStaffNo(staff.getStaffNo());
            staffDto.setStaffName(staff.getStaffName());
            staffDto.setStaffTel(staff.getStaffTel());
            staffDto.setStaffMobile(staff.getStaffMobile());
            staffDto.setIsSuper(staff.getIsSuper());
            staffDto.setLoginTime(new Date());
            return ResponseBean.success(staffDto);
        } else {
            return ResponseBean.failWithMessage(ReturnCode.USER_ERROR);
        }
    }
}
